﻿//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="DylanBox">
// Copyright (c) DylanBox Corporation. All rights reserved.
// </copyright>
// <summary></summary>
// <reference>
//    http://www.jaggersoft.com/pubs/ExceptionHandlingInCSharp.htm

//      1. how to implement Disposability in our own classes. 
//      2. implicit conversion operator
//      3. Object Adapter pattern.

// </reference>
// <author>Dylan</author>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace MyIDisposable
{
    class Program
    {
        static void Main(string[] args)
        {
        }

        private static char[] ReadSource(string filename)
        {
            FileInfo file = new FileInfo(filename);
            int length = (int)file.Length;
            char[] source = new char[length];

            // implicit coversion
            using (AutoTextReader tr = file.OpenText())
            {
                tr.TextReader.Read(source, 0, length);
            }

            return source;
        }
    }

    /// <summary>
    /// how to implement Disposability in our own classes. 
    /// use Object Adapter pattern. 
    /// </summary>
    public sealed class AutoTextReader : IDisposable
    {
        public AutoTextReader(TextReader target)
        {
            // PreCondition(target != null);
            adaptee = target;
        }

        /// <summary>
        /// create an implicit conversion operator: 
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public static implicit operator AutoTextReader(TextReader target)
        {
            return new AutoTextReader(target);
        }

        public TextReader TextReader
        {
            get { return adaptee; }
        }

        /// <summary>
        ///  Adapter pattern works here
        ///  client call AutotextReader's Dispose, actually call adaptee.Close()
        /// </summary>
        public void Dispose()
        {
            adaptee.Close();
        }

        /// <summary>
        /// this is adapter memeber
        /// </summary>
        private readonly TextReader adaptee;     
    }
}
